package lesson28;

import java.util.concurrent.*;

public class ThreadException {



    public static void main(String[] args) {

        ThreadFactory threadFactory = new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                Thread thread = Executors.defaultThreadFactory().newThread(r);
                thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
                    @Override
                    public void uncaughtException(Thread t, Throwable e) {
                        throw new RuntimeException("运行时异常");
                    }
                });
                return thread;
            }
        };

        /* 1、 // execute 会抛出异常， submit 不会抛出异常,submit只有在调用future.get()才会抛出异常， 且线程的异常在主线程中无法被捕获处理

        ExecutorService executorService = Executors.newFixedThreadPool(1);

        try{
            executorService.execute(() -> System.out.println(1/0));
        }catch (Exception e){
            //e.printStackTrace();
        }

        Future future = executorService.submit(() -> System.out.println(1/0));
        try {
            future.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }*/

         // 2、 //在使用 ThreadFactory 的情况下 submit 异常可以被处理

        ExecutorService executorService = Executors.newFixedThreadPool(1, threadFactory);

        executorService.execute(() -> System.out.println(1/0));

        Future future = executorService.submit(() -> System.out.println(1/0));

        try {
            future.get();
        }catch (RuntimeException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}
